/**
 * Summary.js
 *
 * This file contains all of the information and functions related to the summary pane 
 * in the window.
 * 
 * @author Ben Co, Ben Gadbois, Michael Liedtke, Julia Weimar-East
 * 
 */

var cs441GoogleMapsViz = cs441GoogleMapsViz || {};

//Eid for the student layer
var eid;


//column names of the student fusion table
var gpa = 'HS_GPA';
var satmath = 'SAT_MAth';
var satverbal = 'SAT_Verbal';

//Query constants for data look up
var queryHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryTail = '&jsonCallback=?';

//Data
var dataObj = {};


//function to display summary information when querying students


/*
 * studentIds()
 * 
 * This function displays the summary information when querying students.
 */
function studentSummary() {
    eid = cs441GoogleMapsViz.studentEID;
    //query for aggregate information
    var querySummary = 'SELECT COUNT(), AVERAGE('+gpa+'), MAXIMUM('+gpa+'), MINIMUM('+gpa+'), ' +
	'AVERAGE('+satmath+'), MAXIMUM('+satmath+'), MINIMUM('+satmath+'), ' +
	'AVERAGE('+satverbal+'), MAXIMUM('+satverbal+'), MINIMUM('+satverbal+') ' +
	'FROM ' + eid + ' WHERE ' + createFilter();
    
    var queryUrl = encodeURI(queryHead + querySummary + queryTail);
    
    $.get(queryUrl, modifySummary, "jsonp");
}

var highSchoolEID;
var where;
function highSchoolSummary () {
    $("#dropDown").hide();
    $("#dropDown2").show();
    if ($("#radio-zip").is(":checked")){
	var zip = $("#zipcode").val();
	state = cs441GoogleMapsViz.convertZipToState(zip);
	where = zipQuery();
    }
    else
    {
	var region = $("#state").val();
	state = cs441GoogleMapsViz.convertRegionToState(region);
	where = "State = '" + state +"'"
    }

    highSchoolEID = cs441GoogleMapsViz.tables["schools"][state];    
 
    var querySummary = 'SELECT COUNT() FROM ' +
	highSchoolEID + " WHERE " + where;
    

    var queryUrl = encodeURI(queryHead + querySummary + queryTail);
     
    $.get(queryUrl, modifySummaryHS, "jsonp");
}

function modifySummaryHS(data) {
    if (data.table.rows.length > 0) {
	dataObj = { 
	    count : data.table.rows[0]
	};
	
	var querySummary = "SELECT 'High School', Address FROM "+
	    highSchoolEID + " WHERE " + where;
	
	var queryUrl = encodeURI(queryHead + querySummary + queryTail);
	
	$.get(queryUrl, modifySummaryHS2, "jsonp");
    }
    else {
	if ($("#radio-zip").attr("checked")){
	    zoomArea = "student";
	    addr = $("#zipcode").val().split(/,/)[0];
	}
	else {
	    zoomArea = "state"
	    addr = $("#state").val();
	}
	var overall = '<h2 id="'+addr+'"> Summary <span class="ui-icon ui-icon-circle-zoomin zoom2"></span></h2><p>Displaying 0 results.';
	$("#overall").html(overall);
	$("#innerSummary").html("");
	applyZooms();
    }
}


var zoomArea;
var addr;

function modifySummaryHS2(data) {
    dataObj.highSchools = data.table.rows;
    if($("#sortByDropDown2").val() == "a-z")
    {
	sortBy2("a-z");
    }
    else {
	sortBy2("z-a");
    }
    
    if ($("#radio-zip").attr("checked")){
	zoomArea = "student";
	addr = $("#zipcode").val().split(/,/)[0];
    }
    else {
	zoomArea = "state"
	addr = $("#state").val();
    }    
    fillSummaryHTMLHS();
}

function fillSummaryHTMLHS() {

    var overall = '<h2 id="'+addr+'"> Summary <span class="ui-icon ui-icon-circle-zoomin zoom2"></span></h2>';
    overall += "<p>Displaying " + dataObj.count + " results. </p> ";

    var rest = "";
    for (var i=0; i < dataObj.highSchools.length; i++)
    {
	rest += '<div class="highSchool">' +
	    '<h3 id="' + dataObj.highSchools[i][1]+'">';
	rest += dataObj.highSchools[i][0].length > 20 ? dataObj.highSchools[i][0].substring(0,20) : dataObj.highSchools[i][0] ;
	rest+="<span class=\"ui-icon ui-icon-circle-zoomin zoom\"></span></h3>" +
	    "<p>" +
	    dataObj.highSchools[i][0] + "<br />" + 
	    dataObj.highSchools[i][1] + "<br /><br />" +
	    "</p>" + "</div><br />";
    }
    $("#overall").html(overall);
    $("#innerSummary").html(rest);
    $(".highSchool").accordion({collapsible:true,active:false});
    applyZooms();
}




/*
 * modifysummary()
 * 
 * This is a callback function to find the average, minimum, and maximum values for
 * the queried student information. 
 * 
 * @param data The student information to be analyzed
 */
//callback function for aggregate query
function modifySummary(data) {
    $("#dropDown").show();
    $("#dropDown2").hide();
    if(data.table.rows.length > 0) {
	dataObj = {
	    count : data.table.rows[0][0],
	    gpa : {
		average : data.table.rows[0][1].toFixed(2),
		max : data.table.rows[0][2],
		min : data.table.rows[0][3]
	    },
	    satmath : {
		average : Math.round(data.table.rows[0][4]),
		max : data.table.rows[0][5],
		min : data.table.rows[0][6]
	    },
	    satverbal : {
		average : Math.round(data.table.rows[0][7]),
		max : data.table.rows[0][8],
		min : data.table.rows[0][9]
	    }	
	};

	//next query
	var query = 'SELECT UPortland_UniqueID, HS_GPA, SAT_MAth, SAT_Verbal, Address, Gender, Entry_Year, Planned_Major_Code FROM ' + eid + ' WHERE ' + createFilter();    
	var queryUrl = encodeURI(queryHead + query + queryTail);
	$.get(queryUrl, modifySummary2 , "jsonp");
    }
    else {
	if ($("#radio-zip").attr("checked")){
	    zoomArea = "student";
	    addr = $("#zipcode").val().split(/,/)[0];
	}
	else {
	    zoomArea = "state"
	    addr = $("#state").val();
	}
	var overall = '<h2 id="'+addr+'"> Summary <span class="ui-icon ui-icon-circle-zoomin zoom2"></span></h2><p>Displaying 0 results.';
	$("#overall").html(overall);
	$("#innerSummary").html("");
	applyZooms();
    }
}

/*
 * modifySummary2()
 * 
 * This is a callback function that sorts the student data according to the selected 
 * sort by option on the summary pane. 
 */
function modifySummary2(data) {
    dataObj.students = data.table.rows;
    sortBy($("#sortByDropDown").val());
    fillOverallHTML();
    fillInnerSummrayHTML();
    applyZooms();
}

var zoomArea;
var addr;

/*
 * fillOverallHTML()
 * 
 * This function displays all of the general information on the summary pane for the 
 * queried students. This information includes averages, minimums, and maximums for GPA,
 * SAT Math, and SAT Verbal scores.
 */
function fillOverallHTML() {
    if ($("#radio-zip").attr("checked")){
	zoomArea = "student";
	addr = $("#zipcode").val().split(/,/)[0];
    }
    else {
	zoomArea = "state"
	addr = $("#state").val();
    }
    
    var overall = '<h2 id="'+addr+'"> Summary <span class="ui-icon ui-icon-circle-zoomin zoom2"></span></h2>';
    sortByVal = $("#sortByDropDown").val();
    if(sortByVal.match(/gpa/)){
	overall += "<p>Displaying " + dataObj.count + " results. </p> " +
	    "<p>Average GPA: " + dataObj.gpa.average + "</p>" +
	    "<p>Highest GPA: " + dataObj.gpa.max + "</p>" +
	    "<p>Lowest GPA: " + dataObj.gpa.min + "</p>";
    }
    else if(sortByVal.match(/satm/)){
	overall += "<p>Displaying " + dataObj.count + " results. </p> " +
	    "<p>Average SAT Math: " + dataObj.satmath.average + "</p>" +
	    "<p>Highest SAT Math: " + dataObj.satmath.max + "</p>" +
	    "<p>Lowest SAT Math: " + dataObj.satmath.min + "</p>";
    }
    else if(sortByVal.match(/satv/)){
	overall += "<p>Displaying " + dataObj.count + " results. </p> " +
	    "<p>Average SAT Verbal: " + dataObj.satverbal.average + "</p>" +
	    "<p>Highest SAT Verbal: " + dataObj.satverbal.max + "</p>" +
	    "<p>Lowest SAT Verbal: " + dataObj.satverbal.min + "</p>";
    }
    else {
	overall += "<p>Displaying " + dataObj.count + " results. </p> " +
	    "<p>Average GPA: " + dataObj.gpa.average + "</p>" +
	    "<p>Highest GPA: " + dataObj.gpa.max + "</p>" +
	    "<p>Lowest GPA: " + dataObj.gpa.min + "</p>";
    }
    
    $("#overall").html(overall);
}

/*
 * fillInnerSummrayHTML()
 * 
 * This function displays a list of individual student information on the summary pane.
 */
function fillInnerSummrayHTML() {

    var rest = '';
    for (var i=0; i < dataObj.students.length; i++)
    {
	rest += '<div class="student">' +
	    '<h3 id="' + dataObj.students[i][4]+'">';
	    
	if(sortByVal.match(/gpa/)){
	    rest += "GPA: " + dataObj.students[i][1];
	}
	else if(sortByVal.match(/satm/)){
	    rest += "SAT Math: " + dataObj.students[i][2];	    
	}
	else if(sortByVal.match(/satv/)){
	    rest += "SAT Verbal: " + dataObj.students[i][3];
	}
	else {
	    rest += "ID: " + dataObj.students[i][0];
	}
	var major = cs441GoogleMapsViz.collegeMajors[parseInt(dataObj.students[i][7], 10)] || dataObj.students[i][7];
	rest+="<span class=\"ui-icon ui-icon-circle-zoomin zoom\"></span></h3>" +
	    "<p>" +
	    "<strong>ID</strong>: " + dataObj.students[i][0] + "<br />" + 
	    "<strong>Gender</strong>: " + dataObj.students[i][5] + "<br />" +
	    "<strong>Entry Year</strong>: " + dataObj.students[i][6] + "<br />" +
	    "<strong>Planned Major</strong>: " + major + "<br />" +
	    "<strong>GPA</strong>: " + dataObj.students[i][1] + "<br />" +
	    "<strong>SAT Math</strong>: " + dataObj.students[i][2] + "<br />" +
	    "<strong>SAT Verbal</strong>: " + dataObj.students[i][3] + "<br />" +
	    "</p>" + 
	    "</div><br />";
    }
    $("#innerSummary").html(rest);
    $(".student").accordion({collapsible:true,active:false});
}

/*
 * sortBy()
 * 
 * This function sorts the information displayed on the summary pane based on the chosen
 * option in the window. 
 * 
 * @param sortVal The integer that corresponds with the desired sort option
 */
function sortBy(sortVal) {
    switch(sortVal) {
    case "upid-htl":
	dataObj.students.sort(function(a,b){ return (b[0]-a[0]) });
	break;	
    case "upid-lth":
	dataObj.students.sort(function(a,b){ return (a[0]-b[0]) });
	break;
    case "gpa-htl":
	dataObj.students.sort(function(a,b){ return (b[1]-a[1]) });
	break;
    case "gpa-lth":
	dataObj.students.sort(function(a,b){ return (a[1]-b[1]) });
	break;
    case "satm-htl":
	dataObj.students.sort(function(a,b){ return (b[2]-a[2]) });
	break;	
    case "satm-lth":
	dataObj.students.sort(function(a,b){ return (a[2]-b[2]) });
	break;
    case "satv-htl":
	dataObj.students.sort(function(a,b){ return (b[3]-a[3]) });
	break;	
    case "satv-lth":
	dataObj.students.sort(function(a,b){ return (a[3]-b[3]) });
	break;
    }
}

function sortBy2(sortVal) {
    switch(sortVal) {
    case "a-z":
	dataObj.highSchools.sort(function(a,b){ return (a[0].charAt(0) > b[0].charAt(0)) ? 1 : -1; });
	break;	
    case "z-a":
	dataObj.highSchools.sort(function(a,b){ return (a[0].charAt(0) < b[0].charAt(0))  ? 1 : -1});
	break;
    }
}

/*
 * applyZooms()
 * 
 * This function resets the zoom level of the map based on the interaction with the 
 * summary pane. 
 */
function applyZooms() {
    $(".zoom2").click(function(){
	    var addr = $(this).parent().attr("id");
	    centerAt(cs441GoogleMapsViz.map,addr,cs441GoogleMapsViz.geocoder);
	    if (zoomArea == "student"){
	        cs441GoogleMapsViz.map.setZoom(11);
	    }
	    else {
	        cs441GoogleMapsViz.map.setZoom(6);
	    }
    });
    
    $(".zoom").click(function(){
	event.stopPropagation(); //allow button to be clicked within 
	event.preventDefault();  //accordian
	var addr = $(this).parent().attr("id");
	centerAt(cs441GoogleMapsViz.map,addr,cs441GoogleMapsViz.geocoder);
	cs441GoogleMapsViz.map.setZoom(16);
    });
}

/*
 * dropDownListener()
 * 
 * This function creates a listener for the "sort by" drop down menu on the summary pane.
 */
function dropDownListener() {
    $("#sortByDropDown").change(function(){
	sortBy(this.value);
	fillOverallHTML();
	fillInnerSummrayHTML();   
	applyZooms();
    });
}
function dropDownListener2() {
    $("#sortByDropDown2").change(function(){
	sortBy2(this.value);
	fillSummaryHTMLHS()
	applyZooms();
    });
}


